﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web.Script.Serialization;

namespace Sparrow.VisualStudio.Debugger.RouteVisualizer
{
    [Serializable]
    class MvcRouteTransporter : RouteTransporter
    {
        string Url
        {
            get;
            set;
        }

        Dictionary<string, JsonObject> Constraints
        {
            get;
            set;
        }

        Dictionary<string, JsonObject> DataTokens
        {
            get;
            set;
        }

        Dictionary<string, JsonObject> Defaults
        {
            get;
            set;
        }

        JsonObject RouteHandler
        {
            get;
            set;
        }

        public MvcRouteTransporter(Route route)
        {
            this.Constraints = new Dictionary<string, JsonObject>();
            this.DataTokens = new Dictionary<string, JsonObject>();
            this.Defaults = new Dictionary<string, JsonObject>();

            this.Url = route.Url;

            var json = new JavaScriptSerializer();

            if (route.Constraints != null)
            {
                foreach (var i in route.Constraints)
                {
                    this.Constraints.Add(i.Key, new JsonObject(i.Value));
                }
            }

            if (route.DataTokens != null)
            {
                foreach (var i in route.DataTokens)
                {
                    this.DataTokens.Add(i.Key, new JsonObject(i.Value));
                }
            }

            if (route.Defaults != null)
            {
                foreach (var i in route.Defaults)
                {                       
                    this.Defaults.Add(i.Key, new JsonObject(i.Value));                  
                }
            }

            this.RouteHandler = new JsonObject(route.RouteHandler);
        }

        public override System.Web.Routing.RouteBase Deserialize()
        {
            RouteValueDictionary defaults = new RouteValueDictionary();
            foreach (var i in this.Defaults)
            {
                
                defaults.Add(i.Key, i.Value.Deserialize());
            }

            RouteValueDictionary constraints = new RouteValueDictionary();
            foreach (var i in this.Constraints)
            {
                constraints.Add(i.Key, i.Value.Deserialize());
            }

            RouteValueDictionary dataTokens = new RouteValueDictionary();

            foreach (var i in this.DataTokens)
            {
                dataTokens.Add(i.Key, i.Value.Deserialize());
            }

            IRouteHandler routeHandler = this.RouteHandler.Deserialize() as IRouteHandler;

            return new Route(this.Url, defaults, constraints, dataTokens, routeHandler);
        }
    }
}
